<template>
  <div class="groups">
    <SideNav />
    <div class="main-content">
      <!-- 顶部操作栏 -->
      <div class="action-bar">
        <div class="search-box">
          <i class="fas fa-search"></i>
          <input type="text" placeholder="搜索我的小组..." v-model="searchQuery">
        </div>
        <div class="action-buttons">
          <button class="action-btn join-btn" @click="showJoinGroupDialog">
            <i class="fas fa-user-plus"></i>
            加入小组
          </button>
          <button class="action-btn create-btn" @click="showCreateGroupDialog">
            <i class="fas fa-plus"></i>
            创建小组
          </button>
        </div>
      </div>

      <!-- 我的小组列表 -->
      <div class="section-card">
        <h2>我的小组</h2>
        <div v-if="loading" class="loading-container">
          <div class="loading-spinner"></div>
          <p>加载中...</p>
        </div>
        <div v-else-if="myGroups.length === 0" class="empty-state">
          <i class="fas fa-users-slash"></i>
          <p>您还没有加入任何小组</p>
          <button class="action-btn join-btn" @click="showJoinGroupDialog">
            加入小组
          </button>
        </div>
        <div v-else class="groups-grid">
          <div v-for="group in filteredGroups" :key="group.id" class="group-card">
            <div class="group-header">
              <div class="group-name-circle">{{ group.name }}</div>
              <div class="group-role" :class="group.role">
                {{ getRoleText(group.role) }}
              </div>
            </div>
            <div class="group-info">
              <h3>{{ group.name }}</h3>
              <p class="group-desc">{{ group.description }}</p>
              <div class="group-stats">
                <div class="stat-item">
                  <i class="fas fa-users"></i>
                  <span>{{ group.memberCount !== undefined ? group.memberCount : 0 }}人</span>
                </div>
                <div class="stat-item">
                  <i class="fas fa-code"></i>
                  <span>{{ group.problemCount !== undefined ? group.problemCount : 0 }}题</span>
                </div>
              </div>
            </div>
            <div class="group-actions">
              <button class="primary-btn" @click="enterGroup(group.id)">
                进入小组
              </button>
              <button v-if="group.role === 'admin'" class="secondary-btn" @click="manageGroup(group.id)">
                <i class="fas fa-cog"></i>
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 加入小组弹窗 -->
    <div class="dialog-overlay" v-if="showJoinDialog" @click="showJoinDialog = false">
      <div class="dialog-content" @click.stop>
        <div class="dialog-header">
          <h2>加入小组</h2>
          <button class="close-btn" @click="showJoinDialog = false">
            <i class="fas fa-times"></i>
          </button>
        </div>
        <div class="dialog-body">
          <div class="search-box dialog-search">
            <i class="fas fa-search"></i>
            <input 
              type="text" 
              placeholder="搜索可加入的小组..." 
              v-model="joinGroupSearch"
            >
          </div>
          <div v-if="loading" class="loading-container">
            <div class="loading-spinner"></div>
            <p>加载中...</p>
          </div>
          <div v-else-if="availableGroups.length === 0" class="empty-state">
            <i class="fas fa-search"></i>
            <p>没有找到可加入的小组</p>
          </div>
          <div v-else class="available-groups">
            <div v-for="group in filteredAvailableGroups" 
                 :key="group.id" 
                 class="available-group-item">
              <div class="group-name-circle small">{{ group.name }}</div>
              <div class="group-info">
                <h3>{{ group.name }}</h3>
                <p>{{ group.description }}</p>
                <div class="group-meta">
                  <span><i class="fas fa-users"></i> {{ group.memberCount !== undefined ? group.memberCount : 0 }}人</span>
                  <span><i class="fas fa-code"></i> {{ group.problemCount !== undefined ? group.problemCount : 0 }}题</span>
                </div>
              </div>
              <button 
                class="join-btn" 
                :class="{ 'pending': group.status === 'pending' }"
                :disabled="group.status === 'pending'"
                @click="requestJoinGroup(group.id)"
              >
                {{ getJoinButtonText(group.status) }}
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 创建小组弹窗 -->
    <div class="dialog-overlay" v-if="showCreateDialog" @click="showCreateDialog = false">
      <div class="dialog-content" @click.stop>
        <div class="dialog-header">
          <h2>创建小组</h2>
          <button class="close-btn" @click="showCreateDialog = false">
            <i class="fas fa-times"></i>
          </button>
        </div>
        <div class="dialog-body">
          <form @submit.prevent="createGroup" class="create-group-form">
            <div class="form-group">
              <label>小组名称</label>
              <input 
                type="text" 
                v-model="newGroup.name" 
                placeholder="请输入小组名称"
                required
              >
            </div>
            <div class="form-group">
              <label>小组描述</label>
              <textarea 
                v-model="newGroup.description" 
                placeholder="请输入小组描述"
                rows="4"
                required
              ></textarea>
            </div>
            <div class="form-actions">
              <button type="button" class="cancel-btn" @click="showCreateDialog = false">
                取消
              </button>
              <button type="submit" class="submit-btn">
                创建小组
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import SideNav from '@/components/SideNav.vue'
import { groupApi } from '@/utils/api.js'
import { generateGroupAvatar } from '@/utils/helpers.js'

export default {
  name: 'GroupsView',
  components: {
    SideNav
  },
  data() {
    return {
      searchQuery: '',
      myGroups: [],
      showJoinDialog: false,
      showCreateDialog: false,
      joinGroupSearch: '',
      availableGroups: [],
      newGroup: {
        name: '',
        description: '',
      },
      loading: false,
      userId: null // 假设从登录状态或存储中获取
    }
  },
  computed: {
    filteredGroups() {
      return this.myGroups.filter(group => 
        group.name.toLowerCase().includes(this.searchQuery.toLowerCase())
      )
    },
    filteredAvailableGroups() {
      return this.availableGroups.filter(group => 
        group.name.toLowerCase().includes(this.joinGroupSearch.toLowerCase())
      )
    }
  },
  created() {
    // 假设从登录状态或存储中获取用户ID
    this.userId = localStorage.getItem('userId') || 1;
    this.fetchMyGroups();
  },
  methods: {
    // 获取我的小组（包括创建和加入的）
    async fetchMyGroups() {
      this.loading = true;
      try {
        // 获取我创建的小组
        const createdResponse = await groupApi.getMyCreatedGroups(this.userId);
        // 获取我加入的小组
        const joinedResponse = await groupApi.getMyJoinedGroups(this.userId);
        
        if (createdResponse.result === 'success' && joinedResponse.result === 'success') {
          // 合并小组列表并标记角色
          const createdGroups = createdResponse.groups.map(group => ({
            ...group,
            role: 'admin',
            avatar: generateGroupAvatar(group.name)
          }));
          
          const joinedGroups = joinedResponse.groups.map(group => ({
            ...group,
            role: 'member',
            avatar: generateGroupAvatar(group.name)
          }));
          
          // 创建一个Map用于去重，优先保留管理员角色
          const groupMap = new Map();
          
          // 先添加管理员角色的小组
          createdGroups.forEach(group => {
            groupMap.set(group.id, group);
          });
          
          // 再添加成员角色的小组，但不覆盖已有的管理员角色
          joinedGroups.forEach(group => {
            if (!groupMap.has(group.id)) {
              groupMap.set(group.id, group);
            }
          });
          
          // 转换回数组
          this.myGroups = Array.from(groupMap.values());
        } else {
          console.error('获取小组失败:', createdResponse.message, joinedResponse.message);
        }
      } catch (error) {
        console.error('获取小组出错:', error);
      } finally {
        this.loading = false;
      }
    },
    
    // 获取可加入的小组列表
    async fetchAvailableGroups() {
      this.loading = true;
      try {
        const response = await groupApi.getGroupList();
        if (response.result === 'success') {
          // 过滤掉已加入的小组
          const myGroupIds = this.myGroups.map(g => g.id);
          this.availableGroups = response.groups
            .filter(group => !myGroupIds.includes(group.id))
            .map(group => ({
              ...group,
              avatar: generateGroupAvatar(group.name),
              status: 'available'
            }));
        } else {
          console.error('获取可加入小组失败:', response.message);
        }
      } catch (error) {
        console.error('获取可加入小组出错:', error);
      } finally {
        this.loading = false;
      }
    },
    
    showCreateGroupDialog() {
      this.showCreateDialog = true;
    },
    
    showJoinGroupDialog() {
      this.showJoinDialog = true;
      this.fetchAvailableGroups();
    },
    
    getRoleText(role) {
      const roles = {
        admin: '管理员',
        member: '成员'
      }
      return roles[role] || '成员'
    },
    
    enterGroup(groupId) {
      this.$router.push(`/group/${groupId}`)
    },
    
    manageGroup(groupId) {
      this.$router.push(`/group/${groupId}/manage`)
    },
    
    getJoinButtonText(status) {
      return status === 'pending' ? '等待审核' : '申请加入'
    },
    
    async requestJoinGroup(groupId) {
      try {
        const response = await groupApi.joinGroup(groupId, this.userId);
        if (response.result === 'success') {
          // 更新状态为等待审核
          const group = this.availableGroups.find(g => g.id === groupId);
          if (group) {
            group.status = 'pending';
          }
        } else {
          console.error('申请加入小组失败:', response.message);
        }
      } catch (error) {
        console.error('申请加入小组出错:', error);
      }
    },
    
    async createGroup() {
      try {
        const groupData = {
          name: this.newGroup.name,
          description: this.newGroup.description,
          creator_id: this.userId,
          status: 1
        };
        
        const response = await groupApi.createGroup(groupData);
        
        if (response.result === 'success') {
          // 添加到我的小组列表
          const newGroup = {
            ...response.group,
            role: 'admin',
            avatar: generateGroupAvatar(response.group.name)
          };
          
          this.myGroups.push(newGroup);
          this.showCreateDialog = false;
          
          // 重置表单
          this.newGroup = {
            name: '',
            description: ''
          };
        } else {
          console.error('创建小组失败:', response.message);
        }
      } catch (error) {
        console.error('创建小组出错:', error);
      }
    }
  }
}
</script>

<style scoped>
.groups {
  min-height: 100vh;
  background: #f0f7ff;
}

.main-content {
  margin-left: 60px;
  padding: 20px;
}

.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-box {
  position: relative;
  width: 300px;
}

.search-box i {
  position: absolute;
  left: 12px;
  top: 50%;
  transform: translateY(-50%);
  color: #5b7b9a;
}

.search-box input {
  width: 100%;
  padding: 8px 12px 8px 36px;
  border: 1px solid #e8f4ff;
  border-radius: 6px;
  font-size: 14px;
}

.action-buttons {
  display: flex;
  gap: 12px;
}

.action-btn {
  padding: 8px 16px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  transition: all 0.3s ease;
}

.join-btn {
  background: #3498db;
  color: white;
}

.join-btn:hover {
  background: #2980b9;
}

.create-btn {
  background: #42b983;
  color: white;
}

.create-btn:hover {
  background: #3aa876;
}

.section-card {
  background: white;
  border-radius: 10px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px rgba(164, 208, 246, 0.15);
}

.section-card h2 {
  color: #2c3e50;
  margin-bottom: 20px;
}

.groups-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.group-card {
  background: #f8faff;
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s ease;
}

.group-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(164, 208, 246, 0.2);
}

.group-header {
  position: relative;
  height: 100px;
  background: #e8f4ff;
  display: flex;
  justify-content: center;
  align-items: center;
}

.group-name-circle {
  width: 64px;
  height: 64px;
  border-radius: 50%;
  background: #3498db;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  padding: 8px;
  text-align: center;
  word-break: break-all;
  line-height: 1.2;
}

.group-role {
  position: absolute;
  top: 8px;
  right: 8px;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.group-role.admin {
  background: #fdf6ec;
  color: #e6a23c;
}

.group-tag {
  position: absolute;
  top: 8px;
  right: 8px;
  padding: 2px 8px;
  background: #ff6b6b;
  color: white;
  border-radius: 4px;
  font-size: 12px;
}

.group-info {
  padding: 16px;
}

.group-info h3 {
  color: #2c3e50;
  margin-bottom: 8px;
}

.group-desc {
  color: #5b7b9a;
  font-size: 14px;
  margin-bottom: 12px;
  height: 40px;
  overflow: hidden;
}

.group-stats {
  display: flex;
  gap: 16px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #5b7b9a;
  font-size: 14px;
}

.group-actions {
  padding: 16px;
  display: flex;
  gap: 8px;
}

.primary-btn, .join-btn {
  flex: 1;
  padding: 8px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.primary-btn {
  background: #3498db;
  color: white;
}

.secondary-btn {
  padding: 8px;
  background: #e8f4ff;
  color: #3498db;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.join-btn {
  background: #42b983;
  color: white;
}

.join-btn.pending {
  background: #909399;
  cursor: not-allowed;
}

.join-btn:disabled {
  opacity: 0.7;
}

/* 弹窗样式 */
.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.dialog-content {
  background: white;
  border-radius: 10px;
  width: 90%;
  max-width: 600px;
  max-height: 80vh;
  overflow: hidden;
}

.dialog-header {
  padding: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #e8f4ff;
}

.dialog-body {
  padding: 20px;
  max-height: calc(80vh - 70px);
  overflow-y: auto;
}

.dialog-search {
  margin-bottom: 20px;
  width: 100%;
}

/* 可加入小组列表样式 */
.available-groups {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.available-group-item {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 16px;
  background: #f8faff;
  border-radius: 8px;
}

.group-meta {
  display: flex;
  gap: 16px;
  color: #5b7b9a;
  font-size: 12px;
}

/* 创建小组表单样式 */
.create-group-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-group label {
  color: #2c3e50;
  font-weight: 500;
}

.form-group input,
.form-group textarea {
  padding: 8px 12px;
  border: 1px solid #e8f4ff;
  border-radius: 6px;
  font-size: 14px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 20px;
}

.cancel-btn {
  padding: 8px 24px;
  background: #f8faff;
  color: #5b7b9a;
  border: none;
  border-radius: 6px;
  cursor: pointer;
}

.submit-btn {
  padding: 8px 24px;
  background: #42b983;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
}

.close-btn {
  background: none;
  border: none;
  color: #5b7b9a;
  cursor: pointer;
  font-size: 18px;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.loading-spinner {
  border: 4px solid #f3f3f3;
  border-top: 4px solid #3498db;
  border-radius: 50%;
  width: 40px;
  height: 40px;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.empty-state i {
  font-size: 48px;
  color: #5b7b9a;
  margin-bottom: 16px;
}

.empty-state p {
  color: #5b7b9a;
  font-size: 14px;
  text-align: center;
}

.group-name-circle.small {
  width: 48px;
  height: 48px;
  font-size: 14px;
}
</style> 